#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np

# the API doc is here https://quant.pobo.net.cn/doc?name=api 

#OnStart event, initialize some parameters,like which account to use 
def OnStart(context) : # a strategy must have a OnStart part 
    print "I\'m starting..."
    
    #login the trading account , like "回测期货" meant "back test futures account" 
    context.myacc = None
    g.accountname="回测期货"#set the account name 
    if context.accounts.has_key(g.accountname) : #
        print "login in the account "+str(g.accountname)
        if context.accounts[g.accountname].Login() :
            context.myacc = context.accounts[g.accountname]

def OnMarketQuotationInitialEx(context, exchange,daynight):#event of exchange began to broadcast data
    if exchange != 'SHFE': #filter other data that not from SHFE
        return
    #get the main contract
    g.code = GetMainContract('SHFE', 'au',20) # example gold,"g" meant it's a global variable, that could be used in every function
    # SHFE is for Shanghai Futures Exchange, au is for gold, 20 is for main contract
    #also 0 for current month，1 for next month，2 for next quarter，3 for the quarter after the next quarter，20 for main contract
    #subscribe the bar line data to drive OnBar event 
    #a "main contract" is a contract with top trading volume
    SubscribeBar(g.code, BarType.Day) #subsribe the Bar Line, frequency daily
    
#OnBar event, each new bar data received, will activate this function, like to calculate moving average and decide whether to trade
# on certain signals
def OnBar(context,code,bartype) :
    #Filter the unwanted quote data
    
    if code != g.code:
        return
    dyndata = GetQuote(g.code)#get the price quotes
    #calculate the moving average
    MA = GetIndicator("MA",code,params=(5,10),bar_type = BarType.Day)# calculate MA5 and MA10
    MA1 = MA["MA(5)"] #get the MA5
    MA2 = MA["MA(10)"] #get the MA10
    print "MA(5) is "+str(MA1[-1]) +" MA(10) is "+str(MA2[-1])+" current market price is "+str(dyndata.now)
    if len(MA2)<2:
        return
    #MA5 go above MA10, buy open one lot of gold,with current market price
    elif MA1[-1] >= MA2[-1] and MA1[-2]<MA2[-2]:
        QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,1)
    # MA5 go below MA10,sell close one lot of gold,with current market price
    elif MA1[-1] <= MA2[-1] and MA1[-2]>MA2[-2]:
        QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,1)
